//package com.example.rwq_test;
//
//
//import org.eclipse.paho.mqttv5.client.IMqttToken;
//import org.eclipse.paho.mqttv5.client.MqttClient;
//import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
//import org.eclipse.paho.mqttv5.common.MqttMessage;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.web.socket.config.annotation.EnableWebSocket;
//import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
//import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
//import org.springframework.web.socket.handler.TextWebSocketHandler;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.TextMessage;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//import java.nio.charset.StandardCharsets;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.logging.Logger;
//
//@SpringBootApplication
//@EnableWebSocket
//public class WebRtcServer implements WebSocketConfigurer {
//
//    private static final Logger LOGGER = Logger.getLogger(WebRtcServer.class.getName());
//    private MqttClient mqttClient;
//    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
//    private boolean subscribed = false;
//
//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
//    }
//
//    @PostConstruct
//    public void initMqtt() throws Exception {
//        LOGGER.info("Initializing MQTT client");
//        mqttClient = new MqttClient("tcp://localhost:1883", "java-client");
//        MqttConnectionOptions options = new MqttConnectionOptions();
//        options.setAutomaticReconnect(true);
//        options.setPassword("public123".getBytes(StandardCharsets.UTF_8));
//        options.setUserName("admin");
//        options.setCleanStart(true);
//        options.setConnectionTimeout(10);
//        options.setKeepAliveInterval(60);
//        LOGGER.info("Connecting to MQTT broker");
//        mqttClient.connect(options);
//        LOGGER.info("MQTT connection established");
//    }
//
//    @PreDestroy
//    public void closeMqtt() throws Exception {
//        LOGGER.info("Disconnecting MQTT client");
//        mqttClient.disconnect();
//        mqttClient.close();
//        LOGGER.info("MQTT client closed");
//    }
//
//    public class WebSocketHandler extends TextWebSocketHandler {
//        @Override
//        public void afterConnectionEstablished(WebSocketSession session) {
//            LOGGER.info("WebSocket connection established: " + session.getId());
//            sessions.put(session.getId(), session);
//            if (!subscribed) {
//                try {
//                    LOGGER.info("Subscribing to topic: webrtc/answer");
//                    mqttClient.subscribe("webrtc/answer", 1, (topic, message) -> {
//                        LOGGER.info("Entering MQTT callback for topic: " + topic);
//                        String payload = new String(message.getPayload());
//                        LOGGER.info("Received MQTT message on topic " + topic + ": " + payload.substring(0, Math.min(payload.length(), 100)) + "...");
//                        sessions.values().forEach(s -> {
//                            try {
//                                if (s.isOpen()) {
//                                    LOGGER.info("Sending WebSocket message to session " + s.getId());
//                                    s.sendMessage(new TextMessage(payload));
//                                    LOGGER.info("WebSocket message sent successfully");
//                                } else {
//                                    LOGGER.warning("Session " + s.getId() + " is closed");
//                                }
//                            } catch (Exception e) {
//                                LOGGER.severe("Error sending WebSocket message: " + e.getMessage());
//                            }
//                        });
//                        LOGGER.info("Exiting MQTT callback for topic: " + topic);
//                    });
//                    LOGGER.info("Subscribed to webrtc/answer successfully");
//                    subscribed = true;
//                } catch (Exception e) {
//                    LOGGER.severe("Error subscribing to MQTT: " + e.getMessage());
//                }
//            }
//        }
//
//        @Override
//        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//            LOGGER.info("Received WebSocket message from session " + session.getId() + ": " + message.getPayload().substring(0, Math.min(message.getPayload().length(), 100)) + "...");
//            LOGGER.info("Publishing to MQTT topic: webrtc/offer");
//            mqttClient.publish("webrtc/offer", new MqttMessage(message.getPayload().getBytes()));
//            LOGGER.info("Published to webrtc/offer successfully");
//        }
//
//        @Override
//        public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) {
//            LOGGER.info("WebSocket connection closed: " + session.getId() + ", status: " + status);
//            sessions.remove(session.getId());
//        }
//
//        @Override
//        public void handleTransportError(WebSocketSession session, Throwable exception) {
//            LOGGER.severe("WebSocket transport error for session " + session.getId() + ": " + exception.getMessage());
//        }
//    }
//
//    public static void main(String[] args) {
//        LOGGER.info("Starting Spring Boot application");
//        SpringApplication.run(WebRtcServer.class, args);
//        LOGGER.info("Spring Boot application started");
//    }
//}